package com.newcoretech.platform_service.image_picker

import android.Manifest
import android.app.Activity
import android.app.AlertDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.graphics.PorterDuff
import android.graphics.PorterDuffColorFilter
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.Settings
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.newcore.ncimagepicker.nc_image_picker.getInfoFromPath
import com.newcore.ncimagepicker.nc_image_picker.takePic
import com.newcore.ncimagepicker.nc_image_picker.uriToFilePath
import com.newcoretech.platform_service.R
import com.sangcomz.fishbun.FishBun
import com.sangcomz.fishbun.FishBun.Companion.INTENT_PATH
import com.sangcomz.fishbun.MimeType
import com.sangcomz.fishbun.adapter.image.impl.GlideAdapter
import io.flutter.plugin.common.MethodChannel.Result
import java.io.File


/**  */
class NDImagePicker {
    val permissionsPickImage = 5001
    val permissionsTakePhoto = 5004
    val requestPick = 5002
    val requestTakePhoto = 5003

    private var fileImagePath: File? = null

    private var maxCount: Int = 8
    private var enableCamera: Boolean = false

    fun initParams(arguments: Map<*, *>?) {
        maxCount = arguments?.get("maxCount") as? Int? ?: 8
        enableCamera = arguments?.get("enableCamera") as? Boolean? ?: false
    }


    fun checkPermission(requestCode: Int, activity: Activity): Boolean {
        return if (ContextCompat.checkSelfPermission(
                activity,
                Manifest.permission.READ_EXTERNAL_STORAGE
            ) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(
                activity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            ) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(
                activity,
                Manifest.permission.CAMERA
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            if (Build.VERSION.SDK_INT >= 33) {
                ActivityCompat.requestPermissions(
                    activity,
                    arrayOf(
                        Manifest.permission.READ_MEDIA_IMAGES,
                        Manifest.permission.CAMERA,
                    ),
                    requestCode
                )
            } else {
                ActivityCompat.requestPermissions(
                    activity,
                    arrayOf(
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA,
                    ),
                    requestCode
                )
            }


            false
        } else {
            true
        }
    }

    fun startGallery(activity: Activity) {
        val backDrawable = ContextCompat.getDrawable(activity, R.drawable.ic_arrow_back_black_24dp)
        backDrawable?.colorFilter = PorterDuffColorFilter(Color.BLACK, PorterDuff.Mode.SRC_ATOP)
        FishBun.with(activity)
            .setImageAdapter(GlideAdapter())
            .setPickerSpanCount(4)
            .setMaxCount(maxCount)
            .setActionBarColor(Color.parseColor("#ffffff"), Color.parseColor("#ffffff"), true)
            .setActionBarTitleColor(Color.parseColor("#000000"))
            .setAlbumSpanCount(1, 2)
            .setButtonInAlbumActivity(true)
            .setCamera(enableCamera)
            .exceptMimeType(arrayListOf(MimeType.GIF))
            .setReachLimitAutomaticClose(false)
            .setHomeAsUpIndicatorDrawable(backDrawable)
            .setDoneButtonDrawable(
                ContextCompat.getDrawable(
                    activity,
                    R.drawable.ic_check_black_24dp
                )
            )
            .setAllViewTitle("所有图片")
            .setActionBarTitle("选择图片")
            .textOnImagesSelectionLimitReached("选择图片已达到最大数量")
            .textOnNothingSelected("还没有任何图片")
            .startAlbumWithOnActivityResult(requestPick)

    }

    fun takePicture(context: Activity) {
        val saveDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
        fileImagePath = takePic(context, saveDir?.absolutePath ?: "", requestTakePhoto)
        if (fileImagePath == null) {
            Toast.makeText(context, "设备相机不可用", Toast.LENGTH_SHORT).show()
        }
    }

    fun onActivityResult(
        requestCode: Int,
        resultCode: Int,
        data: Intent?,
        activity: Activity,
        pendingResult: Result?
    ) {
        if (requestCode == requestPick) {
            val photos = data?.getParcelableArrayListExtra<Uri>(INTENT_PATH)
            if (photos?.isNotEmpty() == true) {
                val result = ArrayList<HashMap<String, Any>>(photos.size)
                for (uri in photos) {
                    val map = HashMap<String, Any>()
                    val res = uriToFilePath(activity, uri)
                    val f = File(res?.get("path").toString())
                    map["height"] = res?.get("height") ?: 0
                    map["width"] = res?.get("width") ?: 0
                    map["localPath"] = f.path
                    map["name"] = f.name
                    map["size"] = f.length()
                    map["mimeType"] = when (f.extension) {
                        "jpg" -> "image/jpeg"
                        "png" -> "image/png"
                        else -> "image/*"
                    }
                    result.add(map)
                }
                pendingResult?.success(result)
                return
            }
        } else if (requestCode == requestTakePhoto) {
            if (fileImagePath != null) {
                val map = HashMap<String, Any>()
                val res = getInfoFromPath(fileImagePath!!.absolutePath)
                map["height"] = res["height"] ?: 0
                map["width"] = res["width"] ?: 0
                map["localPath"] = fileImagePath!!.absolutePath
                map["name"] = fileImagePath!!.name
                map["size"] = fileImagePath!!.length()
                map["mimeType"] = when (fileImagePath!!.extension) {
                    "jpg" -> "image/jpeg"
                    "png" -> "image/png"
                    else -> "image/*"
                }
                pendingResult?.success(map)
                return
            }
        }
        pendingResult?.success(null)
    }

    fun onRequestPermissionsResult(
        requestCode: Int,
        grantResults: IntArray,
        activity: Activity
    ) {
        var allAllow = true
        for (res in grantResults) {
            if (res != PackageManager.PERMISSION_GRANTED) {
                allAllow = false
            }
        }
        if (allAllow) {
            if (requestCode == permissionsPickImage) {
                startGallery(activity)
            } else if (requestCode == permissionsTakePhoto) {
                takePicture(activity)
            }
        } else {
            val dialog = AlertDialog.Builder(activity)
                .setTitle("提示")
                .setCancelable(false)
                .setMessage("App需要一些图片读取存储和相机权限，请前往设置里授予该权限")
                .setNegativeButton("前往开启") { dialog, which -> //跳转应用消息，间接打开应用权限设置-效率高
                    val intent = Intent()
                    intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
                    val uri =
                        Uri.fromParts(
                            "package",
                            activity.packageName,
                            null
                        )
                    intent.data = uri
                    activity.startActivityForResult(
                        intent,
                        permissionsPickImage
                    )
                }.setPositiveButton("取消") { dialog, which -> //跳转应用消息，间接打开应用权限设置-效率高
                    Toast.makeText(activity, "存储或相机权限不可用", Toast.LENGTH_SHORT).show()
                    dialog.dismiss()
                }
            dialog.show()
        }
    }


}
